// 浏览器web页面调用手机照相机拍照并且返回base64图片
const webpicture = (width: number = 900) => {
	return new Promise((resolve, reject) => {
		const createInput = document.createElement('input');
		createInput.type = 'file';
		createInput.accept = 'image/*';
		createInput.capture = 'environment';
		createInput.click();
		// 返回拍照获取的图片
		createInput.addEventListener('change', () => {
			const file = createInput.files?.[0];
			if (!file) {
				reject('拍照失败');
				return;
			}
			const reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = () => {
				// 将图片压缩宽度变为900,高度自适应
				const img = new Image();
				img.src = reader.result as string;
				img.onload = () => {
					const canvas = document.createElement('canvas');
					canvas.width = width;
					canvas.height = img.height * (width / img.width);
					const ctx = canvas.getContext('2d')!;
					ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
					resolve(canvas.toDataURL());
				};
			};
		});
	});
};

export default webpicture;
